import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from 'element-plus'
import {
  storeCheckListApi,
  storeCheckStoreApi,
  storeCheckUpdateApi,
  storeCheckDeleteApi,
  storeCheckShowApi,
  storeCheckUpdateStatusApi
} from "@/api/purchaseOrderApi";

export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 20,
    status: null,
    checkNo: null,
    checkType: null,
    sortType: null,
    sortOrder: null,
    createdRangeTime: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true,
    pageSizes: [10,20,50,100]
  });
  const statusOptions = ref([
    {id: 1, name: '盘库中'},
    {id: 2, name: '已完成'},
  ])
  const getTotalNum = (num, text = false) => {

  	if(num === 0) {
  		return text ? num : "info";
  	}else if(num > 0) {
  		return text ? num : "success";
  	}else{
  		return text ? num : "danger";
  	}
  };
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "storeCheckId",
      width: 70,
      sortable: true
    },
    {
      label: "盘点单号",
      prop: "checkNo",
      minWidth: 130,
    },
    {
      label: "盈亏数",
      prop: "totalNum",
      cellRenderer: ({ row }) => (
        <el-tag size="small" type={getTotalNum(row.totalNum)} effect="light">
          {getTotalNum(row.totalNum*1, true)}
        </el-tag>
      ),
      minWidth: 100,
      sortable: true
    },

    {
      label: "盘点类型",
      prop: "checkTypeStr",
      minWidth: 130,
    },
    {
      label: "盘点状态",
      prop: "status",
      minWidth: 130,
      cellRenderer: ({ row }) => (
        <span style={row.status === 1?'color:#e6a23c':'color:#67c23a'}>
          {row.status===1?'盘库中':'已完成'}
        </span>
      ),
      sortable: true
    },
    {
      label: "创建时间",
      prop: "createdAt",
      sortable: true,
      minWidth: 150
    },

    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 180
    }
  ];

  function handleSizeChange(val: number) {
    form.page = 1;
    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    let params: any = {
      page: form.page,
      perPage: form.perPage,
      createdStartAt: form.createdRangeTime ? form.createdRangeTime[0] + ' 00:00:00' : null,
      createdEndAt: form.createdRangeTime ? form.createdRangeTime[1] + ' 23:59:59' : null,
      status: form.status,
      checkNo: form.checkNo,
      checkType: form.checkType,
      sortType: form.sortType,
      sortOrder: form.sortOrder
    }
    if(params.checkType === 2) {
      params.storeId = 1
    }
    const res: any = await storeCheckListApi(cleanEmptyData(params));
    dataList.value = res?.result.list;
    pagination.total = res?.result.total;
    pagination.pageSize = res?.result.perPage*1;
    // pagination.currentPage = res?.result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.page = 1;
    form.status = null;
    form.checkNo = null;
    form.checkType = null;
    form.sortType = 'id';
    form.sortOrder = null;
    form.createdRangeTime = null;
    formEl.resetFields();
    onSearch();
  };
  // 删除参数为空的键值
  function cleanEmptyData(obj: object) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '') {
        delete obj[key];
      }
    });
    return obj
  }
  async function openDialog(title = "创建订单", row?: FormItemProps) {
    if(title === '执行') {
      ElMessageBox.confirm('确定继续进行此操作?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      .then(() => {
        storeCheckUpdateStatusApi({ storeCheckId: row.storeCheckId, status: 2 }).then((res: any) => {
          if(res?.code === 200) {
            message(`操作成功`, { type: "success" });
            onSearch();
          }
        });
      })
      return
    }
    let formInline = {
      title: title,
      storeCheckId: row?.storeCheckId ?? null,
      checkNo: row?.checkNo ?? null,
      checkType: row?.checkType ?? 1,
      storeId: row?.storeId ?? null,
      status: row?.status ?? 1,
      productList: row?.productList ?? [{productId: null,realNumber: null,storeId: 1, remarks: null}],
      detaileInfo: null
    };
    if(title === '编辑订单' || title === '订单详情') {
      const res: any = await storeCheckShowApi({
        storeCheckId: row.storeCheckId
      })
      // let arr = [];
      for (let item of res?.result?.checkProducts) {
        // arr.push({
        //   productId: item.productId,
        //   realNumber: item.realNumber,
        //   storeId: item.storeId,
        //   remarks: item.remarks
        // })
        item.productId = item?.product?.id;
        item.productInfo = item.product;
        item.productName = item.product?.productName;
      }
      formInline.productList = res?.result?.checkProducts;
      formInline.detaileInfo = res?.result
    }

    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      top: '5%',
      width: "80%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      hideFooter: title === '详情' ? true : false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            for (let item of curData.productList) {
              if(!item.productId) {
                message('请选择产品', {
                  type: "warning"
                });
                return
              }

              if(!item.storeId) {
                message('请选择仓库', {
                  type: "warning"
                });
                return
              }
              // if(!item.remarks) {
              //   message('请输入备注', {
              //     type: "warning"
              //   });
              //   return
              // }
            }
            let productList = []
            for (let item of curData.productList) {
              productList.push({
                productId: item.productId,
                realNumber: (item.realNumber*1).toFixed(4),
                storeId: item.storeId,
                remarks: item.remarks || '',
              })
            }
            let params = {
              storeCheckId: curData.storeCheckId,
              checkNo: curData.checkNo,
              checkType: curData.checkType,
              storeId: curData.storeId,
              status: curData.status,
              productList: productList
            }
            if (title === "创建订单") {
              storeCheckStoreApi(cleanEmptyData(params)).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else {
              storeCheckUpdateApi(cleanEmptyData(params)).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();

  });

  function handleDelete(row) {
    ElMessageBox.confirm('确定继续进行删除操作?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      storeCheckDeleteApi({ storeCheckId: row.storeCheckId }).then((res: any) => {
        if(res?.code === 200) {
          message(`删除成功`, { type: "success" });
          onSearch();
        }
      });
    })
  }
  function sortChange (column, prop, order) {
    form.sortOrder = "";
    if (column.order == "descending") {
      form.sortOrder = "desc";
      if (column.prop === "storeCheckId") {
        form.sortType = "id";
      } else if(column.prop === 'totalNum') {
        form.sortType = "total_num";
      } else if(column.prop === 'createdAt') {
        form.sortType = "created_at";
      } else if(column.prop === 'status') {
        form.sortType = "status";
      } else {
        form.sortType = column.prop;
      }
    } else if (column.order == "ascending") {
      form.sortOrder = "asc";
      if (column.prop === "storeCheckId") {
        form.sortType = "id";
      } else if(column.prop === 'totalNum') {
        form.sortType = "total_num";
      } else if(column.prop === 'createdAt') {
        form.sortType = "created_at";
      } else if(column.prop === 'status') {
        form.sortType = "status";
      } else {
        form.sortType = column.prop;
      }
    } else {
      form.sortOrder = "";
      form.sortType = "";
    }
    onSearch()
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
    statusOptions,
    sortChange
  };
}
